//
//  FZRefreshControl.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/4/1.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit

let refreshViewHeight : CGFloat = 50

enum RefreshStateType {
    case pull
    case load
    case back
}
class FZRefreshControl: UIControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor.red
        
        setupUI()
    }
    
    fileprivate lazy var indikatorImg : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    fileprivate lazy var messageLab : UILabel = {
      let lab = UILabel()
      lab.text = "下拉刷新"
      lab.font = UIFont.systemFont(ofSize: 13)
      lab.textColor = UIColor.darkGray
      return lab
    }()
    
    fileprivate lazy var UpReloadView : UIActivityIndicatorView = {
        
      let upView = UIActivityIndicatorView(activityIndicatorStyle:.gray)
        
      return upView
    }()
    //默认下拉刷新
    fileprivate var refreshType : RefreshStateType = .pull {
        
        didSet {
            if refreshType == .pull {
                //下拉刷新,箭头重置,字改为"下拉刷新"
                UpReloadView.stopAnimating()
                indikatorImg.isHidden = false
                self.indikatorImg.transform = CGAffineTransform.identity
                messageLab.text = "下拉刷新"
                
                if oldValue == .load {
                    
                    UIView.animate(withDuration: 0.4, animations: {
                        
                        self.superScrView?.contentInset.top -= refreshViewHeight
                    })

                }
            }
            
            if refreshType == .load {
                
               UpReloadView.startAnimating()
               indikatorImg.isHidden = true
               messageLab.text = "加载数据中.."
                
                UIView.animate(withDuration: 0.4, animations: {
                    
                    self.superScrView!.contentInset.top += refreshViewHeight
                    
                }, completion: { (_) in
                    
                    self.refreshType = .pull
                    self.sendActions(for: .valueChanged)
                })
            }
            
            if refreshType == .back {
                
               UIView.animate(withDuration: 0.25, animations: { 
                
                 self.indikatorImg.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
               })
              messageLab.text = "松手就刷新"
            }
        }
    }
        
    fileprivate var superScrView : UIScrollView?
    
    func setupUI() {
        
        addSubview(indikatorImg)
        addSubview(messageLab)
        addSubview(UpReloadView)
        
        indikatorImg.translatesAutoresizingMaskIntoConstraints = false
        messageLab.translatesAutoresizingMaskIntoConstraints = false
        UpReloadView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indikatorImg, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -32))
        addConstraint(NSLayoutConstraint(item: indikatorImg, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLab, attribute: .centerX, relatedBy: .equal, toItem: indikatorImg, attribute: .centerX, multiplier: 1, constant: 48))
        addConstraint(NSLayoutConstraint(item: messageLab, attribute: .centerY, relatedBy: .equal, toItem: indikatorImg, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: UpReloadView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -32))
        addConstraint(NSLayoutConstraint(item: UpReloadView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshing() {
        
        refreshType = .pull
    }
}

extension FZRefreshControl {
    
    //这个方法是子视图即将添加到父视图上会调用
    override func willMove(toSuperview newSuperview: UIView?) {
        
        guard let superScrollView = newSuperview as? UIScrollView else{
            return
        }
        
        self.frame = CGRect(x: 0, y: -refreshViewHeight, width: superScrollView.bounds.size.width, height: refreshViewHeight)
        
        //使用KVO
        superScrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
        self.superScrView = superScrollView
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let offsetY = superScrView?.contentOffset.y
        
        let limitY = -(superScrView!.contentInset.top + refreshViewHeight)
        
        if superScrView!.isDragging {
            
            if offsetY! < limitY && refreshType == .pull {
               print("松手就刷新")
                
               refreshType = .back
            }else if offsetY! > limitY && refreshType == .back{
                    print("下拉刷新")
                refreshType = .pull
            }
        
        }else{
            
            if refreshType == .back {
                print("加载数据")
                refreshType = .load
            }

        }
        
    }
    
    
}













